<?php

namespace App\Models;


use App\Observers\Contract\ObserverCleanable;
use App\Observers\OSSCleanObserver;
use App\Services\Utils\OSSable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;

/**
 * Class DeviceDescription - 设备多语言描述
 *
 * @package App\Models
 */
class DeviceDescription extends Model implements ObserverCleanable
{
    use OSSable;

    protected $table = 'device_descriptions';

    protected static $unguarded = true;

    protected $casts = [
        'language_id' => 'int',
        'device_id'   => 'int',
    ];

    protected $oss_columns = ['instruction_img', 'help_img'];

    protected $instruction_img_key_prefix = 'device/instruction/';
    protected $help_img_key_prefix = 'device/help/';

    /**
     * @param string|UploadedFile $image
     *
     * @return void
     * @throws \Exception
     */
    public function setInstructionImgAttribute($image): void
    {
        if (is_file($image)) {
            $file_key = $this->uploadPostFile($image, $this->instruction_img_key_prefix);
            $this->attributes['instruction_img'] = $file_key;
        } else if (is_string($image) && strlen($image)) {
            $this->attributes['instruction_img'] = $image;
        }
    }

    /**
     * @return string|null
     * @throws \Exception
     */
    public function getInstructionImgAttribute(): ?string
    {
        return $this->attributeToStaticUrl('instruction_img');
    }

    /**
     * @param string|UploadedFile $image
     *
     * @return void
     * @throws \Exception
     */
    public function setHelpImgAttribute($image): void
    {
        if (is_file($image)) {
            $file_key = $this->uploadPostFile($image, $this->help_img_key_prefix);
            $this->attributes['help_img'] = $file_key;
        } else if (is_string($image) && strlen($image)) {
            $this->attributes['help_img'] = $image;
        }
    }

    /**
     * @return string|null
     * @throws \Exception
     */
    public function getHelpImgAttribute(): ?string
    {
        return $this->attributeToStaticUrl('help_img');
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * 监听bos清理事件
         */
        self::observe(OSSCleanObserver::class);
    }

    /**
     * @return array
     */
    public function keyCleanColumns(): array
    {
        return $this->oss_columns;
    }
}
